<template>
    <h2 style="align-items: center">采购合同</h2>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <table style="width: 100%; border: 1px solid #ccc">
            <tr>
                <td colspan="3" style="background-color: grey">
                    <h3 style="color: aliceblue">基本信息</h3>
                    <hr />
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="采购合同名称" prop="vendorId">
                        <el-input v-model="form.pcName" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="供应商名称" prop="vendorId" @dblclick="dialogVisible = true">
                        <el-input v-model="form.vName" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="采购合同类别" prop="1">
                        <el-select v-model="form.pcTypes" placeholder="请选择" style="width: 300px">
                            <el-option label="原材料采购" value="0" />
                            <el-option label="成品采购" value="1" />
                            <el-option label="设备采购" value="2" />
                        </el-select>
                    </el-form-item>
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="单据编号" prop="vendorId">
                        <el-input v-model="form.pcNumber" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="是否需要到货质检" prop="1">
                        <el-select v-model="form.pcWhetherQuality" placeholder="请选择" style="width: 300px">
                            <el-option label="不需要质检" :value="false" />
                            <el-option label="需要质检" :value="true" />
                        </el-select>
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="采购人员" prop="vendorId">
                        <el-input v-model="form.cgpeople" style="width: 300px"
                            @dblclick="dialogVisible2 = true; GetSectorList()" />
                    </el-form-item>
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="我方代表" prop="vendorId">
                        <el-input v-model="form.mName" style="width: 300px"
                            @dblclick="dialogVisible2 = true; GetSectorList()" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="对方代表">
                        <el-select v-model="form.pcRepresentParty" style="width: 200px;" placeholder="请选择对方代表">
                            <el-option label="林雅南" :value="1" />
                            <el-option label="刘柏宏" :value="2" />
                            <el-option label="李中冰" :value="3" />
                            <el-option label="黄文隆" :value="4" />
                            <el-option label="谢彦文" :value="5" />
                        </el-select>
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="合同日期" required>
                        <el-col :span="11">
                            <el-form-item prop="2">
                                <el-date-picker v-model="form.pContractsDate" type="date" aria-label="Pick a date"
                                    placeholder="Pick a date" style="width: 500px" />
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="制单日期" required>
                        <el-col :span="11">
                            <el-form-item prop="4">
                                <el-date-picker v-model="form.pcPreparationDate" type="date" aria-label="Pick a date"
                                    placeholder="Pick a date" style="width: 500px" />
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                </td>
            </tr>
        </table>
        <br />
        <table style="width: 100%; border: 1px solid #ccc">
            <tr>
                <td colspan="3" style="background-color: grey">
                    <h3 style="color: aliceblue">金额信息</h3>
                    <hr />
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="产品金额" prop="vendorId">
                        <el-input v-model="form.pcProductPrice" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="优惠总额" prop="vendorId">
                        <el-input v-model="form.pcPreferentialPrice" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="优惠后总额" prop="vendorId">
                        <el-input v-model="form.pcAfterOfferPrice" style="width: 300px" />
                    </el-form-item>
                </td>
            </tr>
        </table>
        <br />
        <div style="height: 50px;">
            <el-button round @click="addhang()">新增行</el-button>
        </div>

        <!-- 产品表格 -->
        <table border="1" style="border-collapse: collapse; width: 1000px; height: 40px;">
            <thead>
                <tr>
                    <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" style="width: 30px;" />
                    </th>
                    <th style="height: 40px;">序号</th>
                    <th>产品名称</th>
                    <th>数量</th>
                    <th>产品的单价</th>
                    <th>票据类型</th>
                    <th>产品的总金额</th>
                    <th>优惠后的单价</th>
                    <th>优惠后的总金额</th>
                    <th>产品的到货日期</th>
                    <th>备注</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in check1" :key="index">
                    <td><input type="checkbox" v-model="ids" style="width: 30px;width: 100%;" @click="huoqu" /></td>
                    <td style=" text-align: center;">{{ index + 1 }}</td>
                    <td>
                        <input v-model="item.pName" type="text" style="height: 40px; width: 100px;text-align: center;"
                            @dblclick="dialogVisible3 = true" />
                    </td>
                    <td>
                        <input v-model="item.spcNum" type="text" style="height: 40px; width: 100px;text-align: center;"
                            @dblclick="dialogVisible3 = true" @input="handleInput" />
                    </td>
                    <td>
                        <input v-model="item.spcPrice" type="text"
                            style="height: 40px; width: 100px;text-align: center;" />
                    </td>
                    <td>
                        <input v-model="item.spcDocumentsType" type="text"
                            style="height: 40px; width: 100px;text-align: center;" />
                    </td>
                    <td>
                        <input v-model="item.spcTotalPrice" type="text"
                            style="height: 40px; width: 100px;text-align: center;" />
                    </td>
                    <td>
                        <input v-model="item.spcAfterPrice" type="text"
                            style="height: 40px;width: 100px;text-align: center;" />
                    </td>
                    <td>
                        <input v-model="item.spcAfterTotalPrice" type="text"
                            style="height: 40px;width: 100px;text-align: center;" />
                    </td>
                    <td>
                        <el-col :span="11">
                            <el-date-picker v-model="item.spcArrivalDate" type="date" aria-label="Pick a date"
                                placeholder="Pick a date" style="height: 40px;width: 200px;text-align: center;" />
                        </el-col>
                    </td>
                    <td><input v-model="item.spcRemark" type="text"
                            style="height: 40px;width: 100px;text-align: center;" />
                    </td>
                </tr>
            </tbody>
        </table>
        <!-- 供应商名称弹框 -->
        <el-dialog v-model="dialogVisible" title="供应商名称" width="1000" style="height: 600px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="4">
                        <el-tree style="max-width: 600px" :data="VendorType" :props="defaultProps"
                            default-expand-all="true" @node-click="handleNodeClick" />
                    </el-col>
                    <el-col :span="20">
                        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" />
                            <el-table-column type="index" label="序号" align="center" />
                            <el-table-column prop="vNumber" label="供应商编号" align="center" />
                            <el-table-column prop="vName" label="供应商名称" align="center" />
                            <el-table-column prop="vendorTypeName" label="供应商分类" align="center" />
                            <el-table-column prop="sName" label="供应商省" align="center" />
                            <el-table-column prop="cName" label="供应商市" align="center" />
                            <el-table-column prop="vContact" label="联系人" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisible = false">
                    保存
                </el-button>
            </template>
        </el-dialog>
        <!-- 我方代表弹框 -->
        <el-dialog v-model="dialogVisible2" title="我方代表" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="4">
                        <el-tree style="max-width: 600px" :data="sectorlist" :props="defaultProps"
                            default-expand-all="true" @node-click="handleNodeClick2" />
                    </el-col>
                    <el-col :span="20">
                        <el-table :data="manpowerList" style="width: 100%" @selection-change="handleSelectionChange2">
                            <el-table-column type="selection" width="55" />
                            <el-table-column type="index" label="序号" align="center" />
                            <el-table-column prop="mName" label="姓名" align="center" />
                            <el-table-column prop="sectorName" label="部门" align="center" />
                            <el-table-column prop="postName" label="岗位" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisible2 = false">
                    保存
                </el-button>
            </template>
        </el-dialog>
        <!-- 产品名称 -->
        <el-dialog v-model="dialogVisible3" title="产品名称选择" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="4">
                        <el-tree style="max-width: 600px" :data="VendorType" :props="defaultProps"
                            default-expand-all="true" @node-click="handleNodeClick" />
                    </el-col>
                    <el-col :span="20">
                        <el-table :data="productlist" border style="width: 100%"
                            @selection-change="handleSelectionChange1">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="pName" label="产品名称" align="center" />
                            <el-table-column prop="pNumber" label="产品编号" align="center" />
                            <el-table-column prop="pUnit" label="规格型号" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisible3 = false">
                    保存
                </el-button>
            </template>
        </el-dialog>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const locationOptions = ["Home", "Company", "School"];
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import http from '../../../http.js'
const route = useRoute();
const router = useRouter();
var dates = new Date();
const dialogVisible = ref(false)    //供应商名称弹框
const dialogVisible2 = ref(false)   //我方代表
const dialogVisible3 = ref(false)//双击产品名称弹出层
// 创建响应式变量
const quantity = ref(0);
const unitPrice = ref(0);
const discountTotal = ref(0);
const form = reactive({
    vName: '',
    mName: '',
    cgpeople: '',
    "purchaseContractsIds": route.query.Ids,
    "vendorId": '',
    "pcName": "",
    "pcTypes": "",
    "pcNumber": "",
    "pcWhetherQuality": '',
    "manpowerId": '',
    "pcOurRepresentatives": '',
    "pcRepresentParty": '',
    "procureApplyId": '',
    "pContractsDate": "",
    "pcPreparationDate": "",
    "pcProductPrice": '',
    "pcPreferentialPrice": '',
    "pcAfterOfferPrice": '',
    "addName": "",
    "addTime": "",
    "office_Id": "",
    "user_Id": '',
    "upddtos": [
        {
            "sourcProductContractId": route.query.sid,
            "productId": '',
            "spcNum": '',
            "spcPrice": '',
            "spcDocumentsType": '',
            "spcTotalPrice": '',
            "spcAfterPrice": '',
            "spcAfterTotalPrice": '',
            "spcArrivalDate": "",
            "sppNumber": "",
            "sppName": "",
            "sppSpec": "",
            "spcRemark": "",
            "addName": "",
            "pcNumber": "",
            "addTime": "",
            "office_Id": "",
            "user_Id": ''
        }
    ]
});
onMounted(() => {
    getVendorType();    //显示供应商
    table();//显示供应���
    ProductList();  //显示产品列表
    GetManpowerList();  //显示人员档案
    getFan();
})
const rules = reactive<FormRules>({
    name: [
        { required: true, message: "Please input Activity name", trigger: "blur" },
        { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
    ],
    region: [
        {
            required: true,
            message: "Please select Activity zone",
            trigger: "change",
        },
    ],
    date1: [
        {
            type: "date",
            required: true,
            message: "Please pick a date",
            trigger: "change",
        },
    ],
});

//取消
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    location.reload();
}
//多选框
const check1 = ref<ProductItem[]>([])
const handleSelectionChange1 = (val: any) => {
    check1.value = val
    console.log(check1.value)
}
//点击新增行
const addhang = () => {
    check1.value.push({
        pName: '',
        spcNum: '',
        spcPrice: '',
        spcDocumentsType: '',
        spcTotalPrice: '',
        spcAfterPrice: '',
        spcAfterTotalPrice: '',
        spcArrivalDate: '',
        spcRemark: '',
    });
}
//全选
const ids: any = ref([])
const selectAll = ref(false)
const toggleSelectAll = () => {
    ids.value = []
    if (selectAll.value) {
        ids.value = check1.value.map(ele => ele.productId)
    }
}
// //点击复选框获取选中的值
// const selectedRows = ref([])
// const huoqu = () => {
//     if (ids.value) {
//         selectedRows.value = check1.value.filter(item => item.productId);
//     }

//     console.log(selectedRows.value)
// }
//#region  产品名称
const productPage = reactive({
    pindex: 1,
    psize: 100,
    pageLast: 0,
    sumCount: 0,
    PName: "",
    PNumber: "",
})
//显示产品列表
const productlist = ref([])
const ProductList = () => {
    axios.get(http.zblnb+'/cg/api/ProcurementReturn/GetProductList', {
        params: {
            pindex: productPage.pindex,
            psize: productPage.psize,
            PName: productPage.PName || "",
            PNumber: productPage.PNumber || "",
            ProductTypeId: 0
        }
    })
        .then(res => {
            productlist.value = res.data.data.list
            productPage.sumCount = res.data.data.sumCount;
            productPage.pageLast = res.data.data.pageLast
            console.log(res.data)
        })
}




//#region  供应商名称弹框
const defaultProps = {
    children: 'children',
    label: 'label',
}
var VendorType = ref([]);
const getVendorType = () => {
    axios.get(http.zblnb+'/cg/api/Vendor/ProductTypeSelect').then(res => {
        if (res.data.code == 0) {
            VendorType.value = res.data.data
        }
        console.log(VendorType.value)
    })
}

//树形
const handleNodeClick = (data: Tree) => {
    console.log(data)
    form.purchaseContractsIds = data.value
}

const formInline = reactive({
    vNumber: '',
    vName: '',
    date: '',
    provinceId: '',
    cityId: '',
    vIndustry: '',
    bPhone: '',
    vPhone: '',
    vContact: '',
    PageIndex: 1,
    PageSize: 10,
    fid: ''
})

//供应商显示
var tableData = ref([]);
const table = () => {
    axios.get(http.zblnb+'/cg/api/Vendor/ProductTypeSelectShow', {
        params: {
            FId: formInline.fid,
            Node: formInline.vNumber,
            Name: formInline.vName,
            Sid: formInline.provinceId,
            Cid: formInline.cityId,
            Hid: formInline.vIndustry,
            BPhone: formInline.bPhone,
            SPhone: formInline.vPhone,
            ZProper: formInline.vContact,
            PageIndex: formInline.PageIndex,
            PageSize: formInline.PageSize
        }
    }).then(res => {

        if (res.data.code == 200) {
            tableData.value = res.data.data.list
        }
        console.log(tableData.value)
    })
}

//多选框
const check = ref([])
const handleSelectionChange = (val: User[]) => {
    check.value = val
    form.vName = check.value[0].vName
    console.log(check.value[0].vName)
    console.log(check.value[0])
    form.vendorId = check.value[0].vendorId
}
//#endregion
//#region  我方代表
//查询条件
const wform = reactive({
    MName: "",
    Mstart: "",
    Mend: "",
    Bstart: "",
    Bend: "",
    SectorId: "",
    PostId: ""
})

//分页
const wPage = reactive({
    Pindex: 1,
    Psize: 10,
    pcount: 0,
    lcount: 0
})

//部门
const sectorlist = ref([])
const GetSectorList = () => {
    axios.get(http.zblnb+'/vendor/api/Post/GetSectorList')
        .then(res => {
            sectorlist.value = res.data.data;
            console.log(sectorlist.value)
        })
}

//树形
const handleNodeClick2 = (data: Tree) => {
    console.log(data)
    wform.SectorId = data.value
    GetManpowerList();
}

//显示人员档案
const manpowerList = ref([])
const GetManpowerList = () => {
    axios.get(http.zblnb+'/vendor/api/Manpower/GetManpowerList', {
        params: {
            Pindex: wPage.Pindex,
            Psize: wPage.Psize,
            MName: wform.MName || "",
            Mstart: wform.Mstart || "",
            Mend: wform.Mend || "",
            Bstart: wform.Bstart || "",
            Bend: wform.Bend || "",
            SectorId: wform.SectorId || "",
            PostId: wform.PostId || "",
        }
    })
        .then(res => {
            manpowerList.value = res.data.data.list
            wPage.lcount = res.data.data.lcount;
            wPage.pcount = res.data.data.pcount;
            console.log(res.data.data)
        })
}


//多选框
const check2 = ref([])
const handleSelectionChange2 = (val: User[]) => {
    check2.value = val
    form.mName = check2.value[0].mName
    form.cgpeople = check2.value[0].mName
    console.log(check2.value[0])
    form.pcOurRepresentatives = check2.value[0].postId
    form.manpowerId = check2.value[0].manpowerId
}


//#endregion


const getFan = () => {
    axios.get(http.zblnb+'/cg/api/PurchaseContracts/FanProcurementReturn?PurchaseContractsIds=' + route.query.Ids).then((res) => {
        console.log(res.data.data)
        console.log(res.data.data.pcName)
        var wtypelists = '';
        switch (res.data.data.manpowerId) {
            case 1:
                wtypelists = '张吉惟6'
                break;
            case 2:
                wtypelists = '林国瑞66'
                break;
            case 4:
                wtypelists = '张萌'
                break;
            case 5:
                wtypelists = '刘柏宏'
                break;
            case 6:
                wtypelists = '王美'
                break;
            case 7:
                wtypelists = '周生'
                break;
            case 8:
                wtypelists = '王伊乐'
                break;
            case 9:
                wtypelists = '陈一一'
                break;
        }
        form.pcName = res.data.data.pcName
        form.pcTypes = res.data.data.pcTypes
        form.pcNumber = res.data.data.pcNumber
        form.vendorId = res.data.data.vendorId
        form.vName = res.data.data.vName
        form.manpowerId = res.data.data.manpowerId
        form.cgpeople = wtypelists
        form.pcOurRepresentatives = res.data.data.pcOurRepresentatives
        form.procureApplyId = res.data.data.procureApplyId
        form.pcWhetherQuality = res.data.data.pcWhetherQuality
        form.mName = wtypelists
        form.pcRepresentParty = res.data.data.pcRepresentParty
        form.pContractsDate = res.data.data.pContractsDate
        form.pcPreparationDate = res.data.data.pcPreparationDate
        form.pcProductPrice = res.data.data.pcProductPrice
        form.pcPreferentialPrice = res.data.data.pcPreferentialPrice
        form.pcAfterOfferPrice = res.data.data.pcAfterOfferPrice
        form.addName = res.data.data.addName
        form.addTime = res.data.data.addTime
        form.office_Id = res.data.data.office_Id
        form.user_Id = res.data.data.user_Id
        check1.value = res.data.data.productLists;
    })
}

//点击复选框获取选中的值
const selectedRows = ref([])
const huoqu = () => {
    if (ids.value) {
        selectedRows.value = check1.value.filter(item => item.productId);
    }
    console.log(selectedRows.value)
}
//添加采购合同
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 过滤出选中的行
            const selectedProducts = check1.value.filter(item => ids.value.includes(item.productId));
            
            const model = {
                purchaseContractsIds: route.query.Ids,
                vendorId: form.vendorId,
                pcTypes: form.pcTypes,
                pcName: form.pcName,
                pcNumber: form.pcNumber,
                pcWhetherQuality: form.pcWhetherQuality,
                manpowerId: form.manpowerId,
                pcOurRepresentatives: form.pcOurRepresentatives,
                pcRepresentParty: form.pcRepresentParty,
                pContractsDate: form.pContractsDate,
                pcPreparationDate: form.pcPreparationDate,
                pcProductPrice: form.pcProductPrice,
                pcPreferentialPrice: form.pcPreferentialPrice,
                pcAfterOfferPrice: form.pcAfterOfferPrice,
                upddtos: selectedProducts.map(item => ({
                    sourcProductContractId: route.query.sid,
                    productId: item.productId,
                    spcNum: item.spcNum,
                    spcPrice: item.spcPrice,
                    spcDocumentsType: item.spcDocumentsType,
                    spcTotalPrice: Number(item.spcNum) * Number(item.spcPrice),
                    spcAfterPrice: Number(item.spcPrice) - Number(form.pcPreferentialPrice),
                    spcAfterTotalPrice: Number(item.spcNum) * (Number(item.spcPrice) - Number(form.pcPreferentialPrice)),
                    spcArrivalDate: item.spcArrivalDate,
                    sppNumber: item.pNumber,
                    sppName: item.pName,
                    sppSpec: item.pSpec,
                    spcRemark: item.spcRemark
                })).filter(item => item.spcNum !== '')
            }

            try {
                const res = axios.post(http.zblnb+'/cg/api/PurchaseContracts/UpdPurchaseContracts', model)
                if (res.data.data > 0) {
                    ElMessage.success('修改成功');
                    router.push('/ShowPurchaseContracts');
                } else {
                    ElMessage.error('修改失败');
                }
            } catch (error) {
                ElMessage.error('提交出错');
                console.error(error);
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

interface Tree {
  value: string | number;
  label: string;
  children?: Tree[];
}

interface User {
  vendorId: number;
  vName: string;
  manpowerId: number;
  mName: string;
  postId: number;
  productId: number;
  pNumber: string;
  pName: string;
  pSpec: string;
}

interface ProductItem {
    productId?: number;
    pName: string;
    spcNum: string | number;
    spcPrice: string | number;
    spcDocumentsType: string;
    spcTotalPrice: string | number;
    spcAfterPrice: string | number;
    spcAfterTotalPrice: string | number;
    spcArrivalDate: string | Date;
    pNumber?: string;
    pSpec?: string;
    spcRemark: string;
}
</script>
